
#include <stdio.h>
#include <stdlib.h>
#include "StringList.h"

#define TempSize 256

StringList::StringList()
	: items(NULL), count(0), index(0), size(TempSize) {
	temp = (unsigned char*) malloc(TempSize);
	if (temp == NULL) {
		fprintf(stderr, "%s(%d) : malloc return null\n", __func__, __LINE__);
	}
}

StringList::~StringList() {
	free(temp);
	if (items != NULL) {
		free(items);
	}
}

void StringList::add(BufferString &str) {
	if (items == NULL) {
		items = (ListItem*) malloc(sizeof(ListItem));
		count = 0;
	} else {
		items = (ListItem*) realloc(items, sizeof(ListItem) * (count + 1));
	}
	if (items == NULL) {
		fprintf(stderr, "%s(%d): malloc return null\n", __func__, __LINE__);
		return;
	}

	items[count].str = str;
	items[count].addr = index;
	count++;

	if (index + 2 + str.length >= size) {
		size += TempSize;
		temp = (unsigned char*) realloc(temp, size);
	}
	if (temp == NULL) {
		fprintf(stderr, "%s(%d): realloc return null\n", __func__, __LINE__);
		return;
	}

	memcpy(temp + index, &str.length, 2);
	index += 2;
	memcpy(temp + index, str.ptr, str.length);
	index += str.length;
}

int StringList::find(BufferString &str) {
	for (int i=0; i<count; i++) {
		if (items[i].str == str) {
			return items[i].addr;
		}
	}
	return -1;
}

int StringList::getAddr(BufferString &str) {
	int addr = find(str);
	if (addr >= 0) {
		return addr;
	}

	add(str);
	return items[count - 1].addr;
}
